package com.btr.ivle.backgroud;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.btr.ivle.data.IVLEToken;

import android.content.Context;
import android.os.AsyncTask;

public class IVLEAuthTask extends AsyncTask<String, Void, List<String>> {
	
	private Context context;
	
	public IVLEAuthTask(Context context){
		this.context = context;
	}
	
    protected List<String> doInBackground(String... texts) {
    	String api_key = texts[2];
    	HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://ivle.nus.edu.sg/api/login/?apikey="+api_key);

        String token= "";
        
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("userid", texts[0]));
            nameValuePairs.add(new BasicNameValuePair("password", texts[1]));
            nameValuePairs.add(new BasicNameValuePair("__LASTFOCUS",""));
            nameValuePairs.add(new BasicNameValuePair("__EVENTTARGET",""));
            nameValuePairs.add(new BasicNameValuePair("__EVENTARGUMENT",""));
            nameValuePairs.add(new BasicNameValuePair("__VIEWSTATE",""));
            nameValuePairs.add(new BasicNameValuePair("__SCROLLPOSITIONX","0"));
            nameValuePairs.add(new BasicNameValuePair("__SCROLLPOSITIONY","0"));
            nameValuePairs.add(new BasicNameValuePair("loginimg1.x","0"));
            nameValuePairs.add(new BasicNameValuePair("loginimg1.y","0"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httppost.addHeader("Origin", "https://ivle.nus.edu.sg");
            httppost.addHeader("Host", "ivle.nus.edu.sg");
            httppost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19");
            httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
            httppost.addHeader("Referer","https://ivle.nus.edu.sg/api/login/?apikey="+api_key);
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            long length = response.getEntity().getContentLength();
            InputStream contentStream = response.getEntity().getContent();
            byte[] b = new byte[10000];
            contentStream.read(b, 0, (int)length);
            token = new String(b,0,(int)length);
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        
        List<String> result = new ArrayList<String>();
    	result.add(token);
    	result.add(texts[0].toUpperCase());
    	
		return result;
        
    }

    @SuppressWarnings("unchecked")
	protected void onPostExecute(List<String> result) {
    	if (result.get(0).length() == 416){
    		IVLEToken.setToken(result.get(0),result.get(1));
    	}else{
    		IVLEToken.unsetToken();	
    	}
    	AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete("");
    }
}